package com.example.util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 自定义ClassLoader
 * @author kangshuai
 */
public final class MyClassLoader extends ClassLoader {

    private String classDir;

    @Override
    public Class<?> findClass(String name) {
        String realPath = classDir + name.replace(".", "/") + ".class";
        byte[] cLassBytes = null;
        Path path = null;

        try {
            path = Paths.get(new URI(realPath));
            cLassBytes = Files.readAllBytes(path);

        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
        Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);
        return clazz;
    }


    public MyClassLoader(String classDir) {
        this.classDir = "file://".concat(classDir);
    }
}